package GDoc::Job::Fetch::US::Legi::CBO::WP;

use Moose;

use WWW::Mechanize;
use GDoc::Job;
use File::Temp;


extends 'GDoc::Job::Fetch::US::Legi::CBO';

sub setup {
    my $self = shift;
    $self->_baseurl( 'http://www.cbo.gov/publications/bydoctype.cfm?dtype=8' );
    $self->_basedir( 'http://www.cbo.gov' );
}

sub run { 
    my $self = shift;
   
    if ( $self->data->{link} ) { 
        $self->_fetch_pdf;
    } else { 
        $self->logger->info( "fetching base " . $self->_baseurl );
        my $mech = $self->_mech;
        $mech->get( $self->_baseurl );
        my @links = $mech->find_all_links( url_regex => qr/doc\.cfm\?index=\d+$/, text_regex => qr{(Technical|Working)\s+Paper\s} );

        foreach my $link( @links ) { 
            my $job = GDoc::Job->new( class => 'Fetch::US::Legi::CBO::WP',
                                      queue => $self->fetch_queue,
                                      data  => { link    => $link->url,
                                                 desc    => $link->text
                                               }
                                    );

            $job->submit;
        }
    }
}


sub _fetch_pdf { 
    my $self = shift;
    my %data = %{ $self->data };

    $data{desc} =~ m{(?:Technical|Working)\s+Paper\s+(?<year>\d{4})-(?<num>\d{1,2}):\s+(?<title>.+?)$};
    my ( $year, $num, $title ) = @+{'year', 'num', 'title'};

    my $ident = sprintf( 'CBO-WP-%04d-%02d', $year, $num );
    my $filename = $ident . '.pdf';
    my $key = 'us/legi/cbo/' . $filename;

    if ( $self->_check_key( $key ) ) { 
        $self->logger->info( "Already have $data{link}, skipping" );
        return;
    }

    $self->logger->info( "Storing $data{link} --> $key" );

    my $mech = $self->_mech;
    my $tmpf = File::Temp->new;
    $mech->get( $self->_basedir . $data{link}, ':content_file' => $tmpf->filename );

    $self->store_pdf( key      => $key,
                      datafile => $tmpf,
                      filename => $filename,
                      meta     => { description   => $title,
                                    identifier    => $ident,
                                  }
                    );

}

1;

